package analyse.database.utility;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Utility class with static utility methods.
 * 
 * @author siid
 */
public class Utility {

	
	/**
	 * Converts the given name (e.g. database fielname or database tablename)
	 * into a java name.<br>
	 * <br>
	 * 
	 * Example:
	 * <li> prefix = get, name = REV_NUM - Return-Value: getRevNum
	 * <li> prefix = set, name = REV_NUM - Return-Value: setRevNum
	 * <li> firstUp = true, prefix = null, name = USER - Return-Value: User
	 * 
	 * @param firstUp
	 *            indicates whether the first character is upper chase or not,
	 *            e.g. true for classname
	 * @param prefix
	 *            a prefix, e.g. get, set
	 * @param name
	 *            the db fieldname
	 * 
	 * @return the converted name
	 */
	public static String createJavaName(boolean firstUp, String prefix,
			String name) {

		StringBuffer aResult = new StringBuffer();
		name = name.trim().toLowerCase();

		if (prefix != null) {
			aResult.append(prefix);
		}

		boolean upperCase = firstUp;
		for (int j = 0; j < name.length(); j++) {
			String aNextCharacter = name.substring(j, j + 1);
			if (aNextCharacter.equals("_")) {
				upperCase = true;
				continue;
			}
			if (upperCase) {
				aNextCharacter = aNextCharacter.toUpperCase();
			}
			aResult.append(aNextCharacter);
			upperCase = false;
		}

		return aResult.toString();
	}

	public static String createJavaNameFromFieldName(boolean firstUp,
			String fieldname) {
		return createJavaName(firstUp, null, fieldname);
	}
	
	/**
	 * 
	 */
	public static URL getResource(Class clazz, String name) {
		if (name == null) {
			throw new IllegalArgumentException("name == null");
		}

		URL aURL = null;

		if (clazz != null) {
			aURL = clazz.getResource(name);

			if (aURL == null) {
				aURL = clazz.getClassLoader().getResource(name);
			}
		}

		if (aURL == null) {
			aURL = ClassLoader.getSystemResource(name);
		}

		return aURL;
	}
	
	public static String getRootFolder() {
		String result = "";
		URL url = Utility.class.getResource("Utility.class");
		result = url.getPath();
		result = result.substring(0, result.lastIndexOf("WEB-INF"));
		if (result.startsWith("file:/")) {
			result = result.substring(6, result.length());
		}
		return result;
	}
}
